package com.example.springboot.controller;

import com.example.springboot.common.Result;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        if(file.isEmpty()){
            return Result.error("图片上传失败");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = "." + originalFilename.split("\\.")[1];
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + ext;
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getParentFile().getAbsolutePath() +
                "\\file\\";
        String path = pre + fileName;
        System.out.println(path);
        try{
            file.transferTo(new File(path));
            return Result.success(fileName);
        }catch (IOException e){
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }

    @PostMapping("/upload2")
    public Result upload2(MultipartFile file){
        if(file.isEmpty()){
            return Result.error("图片上传失败");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = "." + originalFilename.split("\\.")[1];
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = uuid + ext;
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = applicationHome.getDir().getParentFile().getParentFile().getParentFile().getAbsolutePath() +
                "\\file\\lun\\";
        String path = pre + fileName;
        System.out.println(path);
        try{
            file.transferTo(new File(path));
            return Result.success(fileName);
        }catch (IOException e){
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }
}
